#include <stdio.h>
#include <stdlib.h>


#define DOCKER_CPU_USAGE_PATH "/sys/fs/cgroup/cpuacct/cpuacct.usage"

int docker_cpu_usage_get (long long  *cpust)
{
    FILE *fp;
    int n;
    char buff[256] = {0};

    if ((fp = fopen (DOCKER_CPU_USAGE_PATH, "r")) == NULL) {
        return -1;
    }

    fgets (buff, sizeof(buff), fp);

    *cpust = atol(buff);

    fclose(fp);

    return 0;
}


float docker_cpu_usage_rate_get (long long  use)
{
    return (float)use/10000000;
}

int main(int argc, char **argv) 
{
    long long i = 0, usage_1 = 0, usage_2 = 0, *usage, use = 0;
  
    for (i = 1; ;i++) {
        if (i != 0 && i%2 == 0) {
            usage = &usage_2;
            fprintf(stderr, "usage_2\n");
        } else  {
            usage = &usage_1;
            fprintf(stderr, "usage_1\n");
        }

        if (docker_cpu_usage_get(usage) == -1) {
            fprintf(stderr, "docker_cpu_usage_get error!\n");
        }
        fprintf(stderr, "cpuusage:%lu\n", usage);

        if ( i != 0 && i%2 == 0) {
            use = usage_2 - usage_1;
            fprintf(stderr, "=====use:%lu(ns) use_rate:%f\n\n", use, docker_cpu_usage_rate_get(use));
            usage_1 = usage_2 = 0;
        }

        sleep(1);
    } 

    return 0;
}
